package com.lwgk.utils;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
 * created by 赵航
 * 联系微信 微信号：zhao--hang--
 * on 2019/7/12
 * --------------------------------------------------------------------------
 * 描述：这是线程切换工具类
 * 注意事项：运用不当会有内存泄漏的风险，单线程工具类，如果有两个都需要异步操作，就出现排队现象（优点：全局唯一，运行块不卡顿，缺点：任务多的时候需要排队等待）
 */
public class ThreadUtils {

    //单例线程池
    private static Executor executor = Executors.newSingleThreadExecutor();
    private static Handler  handler  = new Handler(Looper.getMainLooper());

    /**
     *  全局只产生一个，优点不卡顿，缺点是：使用不当会导致内存泄漏，任务多的时候，会产生排队
     * @param runnable
     */
    public static void executeSubThread(Runnable runnable) {
        executor.execute(runnable);
    }

    public static void executeMainThread(Runnable runnable) {
        handler.post(runnable);
    }

    private static Executor executorNew;

    /**
     * 每次都会创建一个新的线程池，不用排队，缺点：使用不当会导致内存泄漏
     * @param runnable
     */
    public static void executeNewSubThread(Runnable runnable){
        executorNew = Executors.newCachedThreadPool();
        executorNew.execute(runnable);
    }

}
